package lesson06;

/**
 * 两个线程交替打印,
 * 老师的代码是：先打印， 然后唤醒另一个线程，最后当前线程阻塞
 */
public class SynchronizedDemo2 {

    volatile static boolean t2Started = false;

    public static void main(String[] args) throws Exception {
        char[] cI = "1234567".toCharArray();
        char[] cA = "ABCDEFG".toCharArray();

        Object lock = new Object();

        new Thread(() -> {


            synchronized (lock) {
                while (!t2Started) {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                for (int i = 0; i < cA.length; i++) {
                    System.out.print(cA[i]);
                    try {
                        lock.notify();
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }

                }


                lock.notify();
            }
        }, "t1").start();

        new Thread(() -> {

            synchronized (lock) {
               /* while (t2Started) {
                    try {
                        lock.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }*/

                for (int i = 0; i < cI.length; i++) {
                    System.out.print(cI[i]);
                    t2Started = true;
                    try {
                        lock.notify();
                        lock.wait();


                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                lock.notify();
            }
        },"t2").start();
    }

}
